package dao

import (
	"context"
	"gitee.com/ai-love-save/ai-love-save-back/internal/entity"
	"github.com/google/wire"
	"github.com/jinzhu/copier"
	"gorm.io/gorm"
)

// MenuDaoSet DI
var MenuDaoSet = wire.NewSet(wire.Struct(new(MenuDao), "*"))

// MenuDao dao学院操作结构体
type MenuDao struct {
	DB *gorm.DB
}

type ResMenu struct {
	Title    string
	Icon     string
	Key      string
	Path     string
	Children []Menu
}

// Menu 菜单
type Menu struct {
	ID       int
	FatherID int
	Title    string
	Icon     string
	Key      string
	Path     string
	Children []Menu
}

type (
	Menus []Menu
)

// GetMenu 获取菜单
func GetMenu(menuList Menus, pid int) Menus {
	var treeList Menus
	for _, v := range menuList {
		if v.FatherID == pid {
			child := GetMenu(menuList, v.ID)
			node := Menu{
				ID:       v.ID,
				Title:    v.Title,
				FatherID: v.FatherID,
			}
			node.Children = child
			treeList = append(treeList, node)
		}
	}
	return treeList
}

// NormalQuery dao层查找操作
func (m *MenuDao) MenuQuery(ctx context.Context, authority int) (*[]ResMenu, error) {
	result := new([]entity.Menu)
	var res Menus
	db := m.DB.Model(&entity.Menu{})

	db = db.Where("authority >= ?", authority)
	err := db.Find(result).Error
	if err != nil {
		return nil, err
	}
	err = copier.Copy(res, result)
	if err != nil {
		return nil, err
	}
	res = GetMenu(res, 0)
	info:=new([]ResMenu)
	err = copier.Copy(info, &res)
	if err != nil {
		return nil, err
	}
	return info, nil
}
